<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use srvs\UserService;
use yii\console\Controller;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class HelloController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     */
    public function actionIndex($message = 'hello world')
    {
        //创建websocket服务器对象，监听0.0.0.0:9502端口
        $ws = new \swoole_websocket_server("0.0.0.0", 9502);

        //监听WebSocket连接打开事件
        $ws->on('open', function ($ws, $request) {
            var_dump($request->fd, empty($request->get)?[]:$request->get, $request->server);
            $ws->push($request->fd, "hello, welcome\n");
            echo "push ok";
        });

        //监听WebSocket消息事件
        $ws->on('message', function ($ws, $frame) {
            echo "Message: {$frame->data}\n";
            $ws->push($frame->fd, "server: {$frame->data}");
        });

        //监听WebSocket连接关闭事件
        $ws->on('close', function ($ws, $fd) {
            echo "client-{$fd} is closed\n";
        });

        $ws->start();
    }

    public function actionTest(){
        //$WebSocket=new WebSocket("0.0.0.0", 9502);
        // $WebSocket->connect();
        $us=new UserService();
        echo $us->getAllUser();
    }

    public function actionTestWebSocket(){
        $client=new \Swoole\Client\WebSocket("127.0.0.1", 9502);
        if(!$client->connect())
        {
            echo "connect to server failed.\n";
            exit;
        }
        while (true)
        {
            $client->send("hello world");
			try{
				$message = $client->recv();
				if ($message === false)
				{
					break;
				}
				echo "Received from server: {$message}\n";
			}
			catch(\Exception $ex){
				echo "error";
			}
            
            sleep(1);
        }
        echo "Closed by server.\n";
    }
}
